# 链表节点定义（如果 ListNode 也是预定义的，也可以删除）
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def sortedListToBST(self, head):
        # 计算链表长度
        def get_length(node):
            length = 0
            while node:
                length += 1
                node = node.next
            return length
        
        # 使用列表存储当前节点（Python 2 兼容）
        current = [head]
        n = get_length(head)
        
        # 递归构造 BST
        def build_BST(start, end):
            if start > end:
                return None
            
            mid = (start + end) // 2
            
            # 构造左子树
            left_child = build_BST(start, mid - 1)
            
            # 当前节点作为根节点
            root = TreeNode(current[0].val)
            root.left = left_child
            
            # 移动链表指针
            current[0] = current[0].next
            
            # 构造右子树
            root.right = build_BST(mid + 1, end)
            
            return root
        
        return build_BST(0, n - 1)
        